package jwtx

import (
	"time"

	"github.com/golang-jwt/jwt/v4"
)

func GetToken(secretKey string, iat, seconds, uid, id int64) (string, error) {
	claims := &MyClaims{
		Id:  id,
		Uid: uid,
		Iat: iat,
		Exp: iat + seconds,
	}
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))

}

type JWT struct {
	//Secret     string
	bufferTime int64
	issuer     string
	effectTime int64
}

func NewJWT(secret string, bufferTime int64, issuer string) *JWT {
	return &JWT{
		//Secret: secret,
		bufferTime: bufferTime, issuer: issuer}
}

func (j *JWT) CreateClaims(baseClaims BaseClaims) CustomClaims {
	now := time.Now()
	claims := CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: j.bufferTime,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(now),
			ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(j.effectTime) * time.Second)),
			Issuer:    j.issuer,
		},
	}
	return claims
}

func (j *JWT) CreateToken(claims CustomClaims, secret string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(secret))
}
